package kk.service.impl;

import com.github.pagehelper.PageHelper;
import kk.dao.RoleDao;
import kk.domain.Permission;
import kk.domain.Role;
import kk.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Override
    public List<Role> findAll(Integer pageNum,Integer pageSize) throws Exception {
        PageHelper.startPage(pageNum,pageSize);
        List<Role> roleList = roleDao.findAll();
        return roleList;
    }

    @Override
    public void save(Role role) throws Exception {
        roleDao.save(role);
    }

    @Override
    public Role findById(Integer id) throws Exception {
        Role role = roleDao.findById(id);
        return role;
    }

    @Override
    public void deleteRole(Integer id) throws Exception {
        //  从users_role中间表删除角色
        roleDao.deleteFromUsers_RoleByRoleId(id);
        //  从role_permission中间表删除角色
        roleDao.deleteFromRole_PermissionByRoleId(id);
        roleDao.deleteFromRoleByRoleId(id);
    }

    @Override
    public List<Permission> findOtherPermission(Integer roleId) throws Exception {
        List<Permission> permissionList = roleDao.findOtherPermission(roleId);
        return permissionList;
    }

    @Override
    public void addPermissionToRole(Integer roleId, int[] ids) throws Exception {
        for (int permissionId : ids) {
            roleDao.addPermissionToRole(roleId,permissionId);
        }
    }

    @Override
    public List<Permission> findCanDeletePermission(Integer roleId) {
        List<Permission> permissionList = roleDao.findCanDeletePermission(roleId);
        return permissionList;
    }

    @Override
    public void deletePermissionFromRole(Integer roleId, int[] ids) {
        for (int permissionId : ids) {
            roleDao.deletePermissionFromRole(roleId,permissionId);
        }
    }
}
